﻿using CleanArchitecture.Core.Configuration;
using CleanArchitecture.Core.Interfaces;
using CleanArchitecture.Infrastructure.Entities;
using CleanArchitecture.Infrastructure.Interfaces.Media;
using CleanArchitecture.Web.Backend.BackendApi;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;

namespace ClientApp.Web.Api
{
    public class FileDownloadController : BaseApiController
    {
        private readonly INowaFileProvider _fileProvider;
        private readonly IFileUploadService _fileuploadService;
        public FileDownloadController(INowaFileProvider fileProvider,
            IFileUploadService fileuploadService)
        {
            _fileProvider = fileProvider;
            _fileuploadService = fileuploadService;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="rid">Resource Id from FileUpload</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> DownloadResource(int rid)
        {
            try
            {
                var resource = _fileuploadService.GetFileUploadEntityById(rid);
                if (resource == null)
                    throw new FileNotFoundException(ApiResponseMessages.FileNotFound);
                if (resource.StoreType == EntityEnumConfig.FileStoreType.QiniuCloud)
                    return Content("云存储下载功能尚未开通");
                var seoFileName = resource.SeoFilename;
                var lastPart = MimeTypes.GetSupportFileExtensionByMimeType(resource.MimeType);
                if (!lastPart.StartsWith(".")) lastPart = "." + lastPart;
                string downfileName = string.IsNullOrEmpty(resource.TitleAttribute)
                                    ? seoFileName
                                    : resource.TitleAttribute;
                downfileName = downfileName + lastPart;
                var fileLocalPath = resource.VirtualPath.TrimStart('~') + "/" + $"{seoFileName}{lastPart}";
                fileLocalPath = _fileProvider.GetAbsolutePath(fileLocalPath);
                long fileLength = _fileProvider.FileLength(fileLocalPath); //Included fileExist
                if (fileLength < 0) throw new FileNotFoundException(ApiResponseMessages.FileNotFound);
                //更新下载次数
                resource.DownloadCount += 1;
                _fileuploadService.UpdateFileEntityOnly(resource);
                var memory = new MemoryStream();
                using (var stream = new FileStream(fileLocalPath, FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }
                memory.Position = 0;
                return File(memory, resource.MimeType, downfileName);
            }
            catch(FileNotFoundException)
            {
                Request.Path = CleanArchitecture.Infrastructure.StartupConfig.DefaultRoutePath.PageNotFound404;//"/page-not-found";
                Request.QueryString = QueryString.Empty;
                return Redirect(Request.Path);
            }
        }
    }
}
